<template>
  <div class="page-main">
    <home-nav :userData="userinfo"></home-nav>
    <div class="banner"><span>报工项目附件表</span></div>
    <div class="container">
      <div class="content">
        <div class="nav">
          <ul class="left">
            <li
              v-for="(item, index) of contractIds"
              :key="index"
              :class="['hoverShow', { clickShow: tabIndex == index }]"
              @click="changeNavType(index, item)"
            >
              <span v-if="index == 0">主合同</span>
              <span v-if="index != 0">补充协议{{ index }}</span>
            </li>

            <li
              :class="['hoverShow', { clickShow: tabIndex == contractIds.length }]"
              :key="contractIds.length"
              @click="changeNavType(contractIds.length, -1)"
            >
              <span>管理补充</span>
            </li>
          </ul>
          <!-- <span><a-icon type="sync" /></span> -->
        </div>
        <div class="table-box">
          <div class="btn-box" style="display: flex; padding: 10px 0px">
            <ht-upload
              v-if="checkPermission(['WORK_REPORT_MANAGER']) && tabIndex == contractIds.length"
              ref="myUpload"
              class="upload-demo"
              dbKey="Trd"
              busField="workReport"
              :busType="busType"
              :busKey="projectId + ''"
              ftpKey="ftp"
              v-model="fileList"
              :show-file-list="false"
              :before-upload="beforUpload"
              :on-success="afterUpload"
            >
              <a-button class="hte-btn add-btn" type="primary"> 上传 </a-button>
            </ht-upload>
            <a-button class="hte-btn add-btn" type="primary" @click="handleDownload(contractId)"> 下载 </a-button>
            <a-button
              v-if="checkPermission(['WORK_REPORT_MANAGER'])"
              class="hte-btn add-btn"
              type="primary"
              @click="removeAttachRow()"
            >
              删除
            </a-button>
            <a-button class="hte-btn add-btn" type="primary" @click="changeNavType(tabIndex, contractId)">
              刷新
            </a-button>
          </div>
          <a-table
            class="hte-table-content"
            :columns="tabIndex == contractIds.length ? managerAttachColumns : contractAttachColumns"
            :data-source="attachList"
            :loading="tabLoading"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            size="middle"
            rowKey="id"
            :pagination="false"
          >
            <template slot="previewRender1" slot-scope="text, record">
              <span class="font-active" @click="handlePreview1(record)">
                {{ record.fileName }}
              </span>
            </template>
            <span slot="previewRender" slot-scope="text, record">
              <span class="font-active" @click="handlePreview(record)">
                {{ record.fileName }}
              </span>
            </span>
          </a-table>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import '@/config/upload.install.js'
import Vue from 'vue'
import { getAction, postAction } from '@/api/manage'
import { formatFileSize, endWith } from '@/utils/common.js'
import { ACCESS_TOKEN } from '@/store/mutation-types'
export default {
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
  },
  data() {
    return {
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractFileList',
        badgecount: '',
      },
      projectId: this.$route.params && this.$route.params.projectId,
      contractList: [],
      attachList: [],
      tabIndex: 0, //数据类型：0-待审批，1-已处理，2-我发起的
      tabLoading: false,
      url: {
        loadPurchaseContract: '/hte/contract/loadPurchaseContract',
        loadContractAttach: '/hte/contract/loadContractAttach',
        downLoadBatchWithFileName: '/common/downLoadBatchWithFileName',
      },
      contractAttachColumns: [
        {
          title: '所属附件名称',
          dataIndex: 'formName',
          key: 'formName',
        },
        {
          title: '文件名称',
          dataIndex: 'fileName',
          key: 'fileName',
          scopedSlots: { customRender: 'previewRender1' },
        },
        {
          title: '上传人',
          dataIndex: 'createUser',
          key: 'createUser',
        },
        ,
        {
          title: '上传时间',
          dataIndex: 'createTime',
          key: 'createTime',
        },
      ],
      managerAttachColumns: [
        {
          title: '文件名称',
          dataIndex: 'fileName',
          key: 'fileName',
          scopedSlots: { customRender: 'previewRender' },
        },
        {
          title: '文件大小',
          dataIndex: 'fileSize',
          key: 'fileSize',
        },
        {
          title: '上传人',
          dataIndex: 'createUser',
          key: 'createUser',
        },
        ,
        {
          title: '上传时间',
          dataIndex: 'createTime',
          key: 'createTime',
        },
      ],
      selectedRowKeys: [],
      selectedRows: [],
      urls: {
        project: '/workReport/project/info',
        attachs: '/workReport/attach/attachList',
        editAttach: '/workReport/attach/edit',
        deleteAttach: '/workReport/attach/delete',
        myPermission: '/workReport/project/myPermission',
      },
      contractIds: [],
      contractId: -1,
      fileList: [],
      busType: 'PROJECT_MANAGER',
      permission: [],
      contractPlatForm: {},
    }
  },
  mounted() {
    this.fetchProject()
    this.fetchPermission()
  },
  methods: {
    fetchPermission() {
      getAction(this.urls.myPermission, { projectId: this.projectId }).then((res) => {
        if (res.success) {
          this.permission = res.result
        }
      })
    },
    checkPermission(powers) {
      let hasPower = false
      for (let p of powers) {
        if (this.permission.indexOf(p) > -1) {
          hasPower = true
          break
        }
      }
      return hasPower
    },
    fetchProject() {
      getAction(this.urls.project + '/' + this.projectId, {}).then((res) => {
        if (res.success) {
          this.project = res.result
          this.contractIds = this.project.busKeyHistory.split(',')
          let contractPlatFormList = this.project.contractPlatForm.split(',')
          for (let platForm of contractPlatFormList) {
            let platForms = platForm.split('_')
            this.$set(this.contractPlatForm, platForms[0].trim(), platForms[1].trim())
          }
          this.fetchAttach('PROJECT_CONTRACT', this.projectId + '_' + this.contractIds[0])
          console.info(this.contractPlatForm)
        }
      })
    },
    fetchAttach(busType, busKey) {
      this.tabLoading = true
      getAction(this.urls.attachs + '?busType=' + busType + '&busKey=' + encodeURIComponent(busKey), {})
        .then((res) => {
          this.tabLoading = false
          if (res.code == 200) {
            this.attachList = res.result
          } else {
            this.$messageWorkReport.warning('加载数据异常：' + res.message)
          }
        })
        .catch((e) => {
          this.tabLoading = false
          this.$messageWorkReport.warning('加载数据失败:' + e.message)
        })
    },
    changeNavType(index, contractId) {
      this.tabIndex = index
      this.contractId = contractId
      this.selectedRows = []
      this.selectedRowKeys = []
      if (contractId != -1) {
        this.fetchAttach('PROJECT_CONTRACT', this.projectId + '_' + contractId)
      } else {
        this.fetchAttach('PROJECT_MANAGER', this.projectId)
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    downloadContractAttach(contractId) {
      if (this.selectedRows && this.selectedRows.length > 0) {
        let url = process.env.VUE_APP_PS_API_BASE_URL
        let busKeys = this.selectedRows[0].busKey.split('_')
        console.info(this.contractPlatForm)
        console.info(busKeys[1])
        console.info(this.contractPlatForm[busKeys[1].trim()])
        let platForm = this.contractPlatForm[busKeys[1].trim()]
        if (this.selectedRows.length == 1) {
          if (platForm == 'HIP' || platForm == 'PS') {
            if (this.selectedRows[0].platForm == 'CLOUD') {
              url +=
                '/hte/contract/downloadUnion?id=' +
                this.selectedRows[0].busFk +
                '&platForm=CLOUD' +
                '&fileName=' +
                this.selectedRows[0].fileName
            }
            if (this.selectedRows[0].platForm == 'CLOUDFOLDER') {
              url +=
                '/hte/contract/downloadUnion?id=' +
                this.selectedRows[0].busFk +
                '&platForm=CLOUDFOLDER' +
                '&fileName=' +
                this.selectedRows[0].fileName
            } else {
              url +=
                '/hte/contract/downloadUnion?id=' +
                this.selectedRows[0].busFk +
                '&platForm=HIP' +
                '&fileName=' +
                this.selectedRows[0].fileName
            }
          } else {
            let fk = this.selectedRows[0].busFk
            if (fk.indexOf('_') > -1) {
              fk = fk.split('_')[2]
            }
            url += '/hte/contract/download/' + fk
          }
          window.open(url)
        } else {
          let ids = []
          this.selectedRows.forEach((row) => {
            if (row.busFk.indexOf('_') >= 0) {
              let busFk = row.busFk.split('_')
              if (busFk.length == 3) {
                ids.push(busFk[2])
              }
            } else {
              ids.push(row.busFk)
            }
          })
          if (ids.length > 0) {
            let tempFileName = this.project.contractNumber+"#"+this.project.contractName
            if(this.tabIndex==0){
              tempFileName+="主合同.zip"
            }else{
              tempFileName+="补充协议"+this.tabIndex+".zip"
            }
            if (platForm == 'HIP') {
              let newIds = []
              this.selectedRows.forEach((row) => {
                newIds.push(row.busFk + '_' + row.platForm + '_' + row.fileName.replace('_', '-'))
              })
              url +=
                '/hte/contract/downloadZipUnion?ids=' +
                encodeURIComponent(newIds.join(',')) +
                '&contractId=' +
                contractId
                +"&zipName="+encodeURIComponent(tempFileName)
            } else {
              url += '/hte/contract/downloadZip?ids=' + ids.join(',') + '&contractId=' + contractId +"&zipName="+encodeURIComponent(tempFileName)
            }
            window.open(url)
          }
        }
      }
    },
    handleDownload(contractId) {
      if (this.tabIndex != this.contractIds.length) {
        this.downloadContractAttach(contractId)
      } else {
        if (this.selectedRows.length == 1) {
          let record = this.selectedRows[0]
          if (record.busFk) {
            const token = Vue.ls.get(ACCESS_TOKEN)
            window.open(
              process.env.VUE_APP_API_BASE_URL + '/workReport/attach/download?token=' + token + '&id=' + record.busFk
            )
          }
        } else if (this.selectedRows.length > 1) {
          let ids = []
          this.selectedRows.forEach((r) => {
            ids.push(r.busFk)
          })
          this.doDownLoadBatch(ids.join(','))
        }
      }
    },
    doDownLoadBatch(attachIds, ftpKey = 'ftp') {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame')
      //合同编号+合同名称+列表表头
      let tempFileName = this.project.contractNumber+"#"+this.project.contractName.replace("/","-")+"#管理补充.zip"
      // if (this.zipFileName) {
      //   tempFileName = this.zipFileName + '.zip'
      // } else {
      //   tempFileName = new Date().valueOf() + '.zip'
      // }
      var href =
        this.API_BASE_URL +
        this.url.downLoadBatchWithFileName +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=' +
        ftpKey +
        '&token=' +
        this.$ls.get(ACCESS_TOKEN) +
        '&zipFileName=' +
        encodeURIComponent(tempFileName)
      iframe.src = href
    },
    beforUpload() {
      if (this.selectedRows.length > 1) {
        this.$messageWorkReport.warning('请选择一条记录上传')
        return false
      }
      return true
    },
    afterUpload(response) {
      let record = {}
      if (this.selectedRows.length == 1) {
        record = this.selectedRows[0]
      }
      if (response && response.length > 0) {
        this.$set(record, 'fileName', response[0].fileName)
        this.$set(record, 'filePath', response[0].path)
        this.$set(record, 'fileSize', response[0].size)
        this.$set(record, 'createUser', response[0].uploaderName)
        this.$set(record, 'createUserId', response[0].uploader)
        this.$set(record, 'createTime', response[0].uploadTime)
        this.$set(record, 'busType', 'PROJECT_MANAGER')
        this.$set(record, 'busKey', this.projectId + '')
        this.$set(record, 'busFk', response[0].id)
        this.$set(record, 'platForm', 'HTE')
        postAction(this.urls.editAttach, record).then((res) => {
          if (res.success) {
            this.fetchAttach('PROJECT_MANAGER', this.projectId)
          } else {
            this.$messageWorkReport.error(res.message)
          }
        })
      }
    },
    removeAttachRow() {
      let record = this.selectedRows[0]
      if (record.id) {
        postAction(this.urls.deleteAttach + '/' + record.id, {}).then((res) => {
          if (res.success) {
            this.fetchAttach('PROJECT_MANAGER', this.projectId)
          } else {
            this.$messageWorkReport.error(res.message)
          }
        })
      }
    },
    handlePreview(file) {
      let that = this
      if (
        endWith(file.fileName, 'rar') ||
        endWith(file.fileName, 'zip') ||
        endWith(file.fileName, 'dwg') ||
        endWith(file.fileName, 'tgz')
      ) {
        return true
      }
      let fk = file.busFk
      if (fk.indexOf('_') > -1) {
        fk = fk.split('_')[2]
      }
      let token = Vue.ls.get(ACCESS_TOKEN)
      let url = process.env.VUE_APP_API_BASE_URL + '/common/previewAttach?token=' + token + '&id=' + fk + '&ftpKey=ftp'

      if (file.busKey.indexOf('_') > -1) {
        let busKeys = file.busKey.split('_')
        let platForm = this.contractPlatForm[busKeys[1]]
        if (platForm == 'HIP') {
          url =
            process.env.VUE_APP_API_BASE_URL + '/common/platForm?token=' + token + '&id=' + file.busFk + '&ftpKey=ftp'
        }
      }
      window.open(process.env.BASE_URL + '/pdf/web/viewer.html?file=' + encodeURIComponent(url))
    },
    handlePreview1(file) {
      let that = this
      let fileName = file
      if (
        endWith(file.fileName, 'rar') ||
        endWith(file.fileName, 'zip') ||
        endWith(file.fileName, 'dwg') ||
        endWith(file.fileName, 'tgz')
      ) {
        return true
      }
      let fk = file.busFk
      if (fk.indexOf('_') > -1) {
        fk = fk.split('_')[2]
      }
      let url = process.env.VUE_APP_PS_API_BASE_URL + '/hte/contract/previewAttach?id=' + fk
      if (file.busKey.indexOf('_') > -1) {
        let busKeys = file.busKey.split('_')
        let platForm = this.contractPlatForm[busKeys[1]]
        if (platForm == 'HIP' || platForm == 'PS') {
          if (file.platForm == 'CLOUD') {
            platForm = 'CLOUD'
          } else if (file.platForm == 'CLOUDFOLDER') {
            platForm = 'CLOUDFOLDER'
          } else {
            platForm = 'HIP'
          }
          url =
            process.env.VUE_APP_PS_API_BASE_URL +
            '/hte/contract/previewAttachUnion?id=' +
            file.busFk +
            '&platForm=' +
            platForm +
            '&fileName=' +
            file.fileName
        }
      }
      window.open(process.env.BASE_URL + '/pdf/web/viewer.html?file=' + encodeURIComponent(url))
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
.page-main {
  .banner {
    background-image: url(~@assets/contract-top.png);
  }
  .container {
    position: relative;
    .nav {
      border-bottom: 1px solid #e6e6e6;
      display: flex;
      justify-content: space-between;
      width: 100%;
      align-items: center;
      padding: 0;
      background-color: #fff;
      .left {
        padding: 0;
        margin: 0;
        li {
          padding: 10px 20px;
          font-size: 16px;
          color: #333;
          &.clickShow {
            border-bottom: 2px solid #1890ff;
            cursor: pointer;
          }
        }
      }
      > span {
        cursor: pointer;
        margin-right: 26px;
      }
    }
  }
  /deep/ .ant-btn > .anticon + span {
    margin-left: 3px;
  }
}
.font-active {
  cursor: pointer;
}
</style>
